﻿using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using XLZF.MicroServices.Models;

namespace XLZF.MicroServices.IDS4.Controllers
{
    /// <summary>
    /// login
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;

        private readonly ApplicationDbContext _dbContext;

        /// <summary>
        /// login
        /// </summary>
        public LoginController(UserManager<ApplicationUser> userManager = null, ApplicationDbContext dbContext = null)
        {
            // 添加用户管理器
            _userManager = userManager;

            _dbContext = dbContext;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userLogin"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Login([FromBody] UserLoginView userLogin)
        {
            var client = new HttpClient();

            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5231");

            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
            }

            //资源拥有者凭据（username or password)
            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = disco.TokenEndpoint,
                ClientId = "Harris_Client_Pass_ID",
                ClientSecret = "Harris123456",
                UserName = userLogin.userName,
                Password = userLogin.passWord
            });

            if (tokenResponse.IsError)
            {
                Console.WriteLine(disco.Error);

                var errobj = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorModel>(tokenResponse.Json.ToString());

                return BadRequest(errobj.error_description);
            }

            Console.WriteLine(tokenResponse.Json);

            client.SetBearerToken(tokenResponse.AccessToken);

            var apiResourceResponse = await client.GetAsync(disco.UserInfoEndpoint);

            if (!apiResourceResponse.IsSuccessStatusCode)
            {
                Console.WriteLine(apiResourceResponse.StatusCode);

                return BadRequest("");
            }
            else
            {
                var content = await apiResourceResponse.Content.ReadAsStringAsync();

                var objs = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginUserSub>(content);

                var LoginedAccess = new LoginedAccess()
                {
                    NickName = objs.name,
                    TokenAccess = tokenResponse.AccessToken,
                    userid = objs.sub
                };

                return Ok(LoginedAccess);
            }
        }


        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("[action]")]
        public async Task<IActionResult> LoginOutSelf()
        {
            try
            {
                return Ok();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="changePassword"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]

        public async Task<IActionResult> ChangePassword([FromBody] ChangePassword changePassword)
        {
            var user = _dbContext.Users.Where(p => p.Id == Convert.ToInt32(changePassword.ID)).ToList();

            if (user != null && user.Count > 0)
            {
                var result = await _userManager.ChangePasswordAsync(user[0], changePassword.currentPassword, changePassword.newPassword);

                if (result.Succeeded)
                {
                    return Ok();
                }
                else
                {
                    if (result.Errors != null)
                    {
                        string err = string.Empty;

                        foreach (var item in result.Errors)
                        {
                            err += item.Description + "  ";
                        }

                        return BadRequest(err);
                    }

                    return BadRequest("未知错误");
                }
            }
            else
            {
                return BadRequest("没有查询到当前患者信息");
            }
        }
    }
}
